var bookdata = []; //require("bookdata");
var xhrutils = require('xhrutils');
const common = require('common');
const md5 = require('md5');
cc.Class({
  extends: cc.Component,

  properties: {

    book: {
      default: null,
      type: cc.Node
    },
    pagenum: {
      default: null,
      type: cc.Label
    },

    playLabel: {
      default: null,
      type: cc.Node
    },

    auto: true, //默认自动，可从localstrage中取得
    orgcs: 0,
    orgce: 0,
    explaincs: 0,
    explaince: 0,
    currentpage: 1,
    status: 0 //0:正常，1：正加载

  },

  // use this for initialization
  onLoad: function() {
    var self = this;
    var book = this.book; //节点

    /**
     * 测试用数据
     */
    cc.log('book common ' + common.init);
    // var book_id =  common.current_bookid ;
    var book_page = parseInt(common.init.current_page); //0 表示还没有看过
    bookdata = common.init.bookdata;
    //由于删除书的问题，要将index改为id 
    cc.log('book_id' + common.init.current_bookid);
    var bookjson = [];

    for (var i = 0; i < bookdata.length; i++) {
      if (bookdata[i].id == common.init.current_bookid) {
        bookjson = bookdata[i];
        break;
      }
    }
    cc.log('bookjson.pages.length' + bookjson.pages.length);

    //最后一页
    if (book_page > bookjson.pages.length) {
      book_page = bookjson.pages.length;
    }
    self.bookjson = bookjson;
    self.currentpage = book_page;

    //开始读书了，则需要重新改写一下书架的图书排序，将此书往前放
    this.writeBookDataFile(common.init.current_bookid);
  },
  next: function() {
    let self = this;
    if (self.currentpage + 1 > self.bookjson.pages.length) return true;
    //self.unscheduleAllCallbacks();
    self.currentpage = self.currentpage + 1;
    self.gotopage(self.currentpage - 1);
  },
  prev: function() {
    let self = this;
    if (self.currentpage - 1 <= 0) return true;
    // self.unscheduleAllCallbacks();
    self.currentpage = self.currentpage - 1;
    self.gotopage(self.currentpage - 1);
  },
  menu: function() {
    //声音不自动释放
    //if (cc.audioEngine.isMusicPlaying()) {
    cc.audioEngine.uncacheAll();
    //}
    cc.director.loadScene("bookstore");
  },
  reload: function() {
    let self = this;
    // let clipurl = cc.url.raw('resources/' + self.bookjson.path + "/" + self.bookjson.pages[self.currentpage - 1].clip + '.mp3');
    // if (self.bookjson.perfix) {
    //   clipurl = self.bookjson.perfix + self.bookjson.path + "/" + self.bookjson.pages[self.currentpage - 1].clip + '.mp3'
    //   clipurl = jsb.fileUtils.getWritablePath() + 'img/' + md5(clipurl) + '.mp3';
    // }
    // if (cc.audioEngine.isMusicPlaying()) {
    //   cc.audioEngine.stopMusic();
    // }
    // let clip = cc.loader.getRes(clipurl);
    // cc.audioEngine.playMusic(clip);
    cc.audioEngine.pauseAll();

    cc.audioEngine.setCurrentTime(self.orgclipId, self.bookjson.pages[self.currentpage - 1].orgcs);
    cc.audioEngine.setVolume(self.orgclipId, 1);
    cc.audioEngine.resume(self.orgclipId);
    // 重置starttime

    // self.orgclipEnd=
    // cc.audioEngine.rewindMusic();
    if (self.auto) {
      self.playLabel.getComponent(cc.Label).string = '手动';
    }
    self.auto = false;
  },
  close: function() {
    try {
      if (cc.sys.isNative) {
        cc.director.end();
      }
      if (cc.sys.isBrowser) {
        window.close();
      }
    } catch (e) {}
  },

  play: function() {
    let self = this;
    if (self.auto) {
      self.playLabel.getComponent(cc.Label).string = '手动';
    } else {
      self.playLabel.getComponent(cc.Label).string = '自动';
      self.autoplay();
    }
    self.auto = !self.auto;
  },
  explain: function() {
    let self = this;
    self.playLabel.getComponent(cc.Label).string = '手动';
    self.auto = false;
    //self.unscheduleAllCallbacks(); //function(){cc.log('stop clip')});
    //}
    //if (cc.audioEngine.isMusicPlaying()) {
    cc.audioEngine.pauseAll();
    //}
    //原来只是下载到了本地，不在资源里，也只能在本地播放android
    // let clipurl = cc.url.raw('resources/' + self.bookjson.path + "/" + self.bookjson.pages[self.currentpage - 1].explain + '.mp3');
    // if (self.bookjson.perfix) {
    //   clipurl = self.bookjson.perfix + self.bookjson.path + "/" + self.bookjson.pages[self.currentpage - 1].explain + '.mp3';
    //   clipurl = jsb.fileUtils.getWritablePath() + 'img/' + md5(clipurl) + '.mp3';
    // }

    // let clip = cc.loader.getRes(clipurl);
    // cc.log('expain:' + clip + clipurl);
    // cc.audioEngine.playMusic(clip);
    cc.log('self.explainclipId->' + self.explainclipId + ' explaincs:' + self.bookjson.pages[self.currentpage - 1].explaincs + ' state:' + cc.audioEngine.getState(self.explainclipId));
    cc.audioEngine.setCurrentTime(self.explainclipId, self.bookjson.pages[self.currentpage - 1].explaincs);
    cc.audioEngine.setVolume(self.explainclipId, 1);
    self.explaince = self.bookjson.pages[self.currentpage - 1].explaince;
    cc.audioEngine.resume(self.explainclipId);
  },
  //这个慢了
  start: function() {
    let self = this;

    //这里原来是每一帧的音频，现在改成本书的音频，这里只下音频
    let clipurl = self.bookjson.perfix + self.bookjson.path + "/" + self.bookjson.orgclip;
    let explainurl = self.bookjson.perfix + self.bookjson.path + "/" + self.bookjson.explainclip;
    cc.log('clipurl:' + clipurl);
    let urls = [clipurl];
    if (self.bookjson.explainclip) {
      urls.push(explainurl);
    }
    //先把音频下载完成再进行页面
    xhrutils.loadAll(urls, function(rs) {
      //增加音频控制
      let filepath = jsb.fileUtils.getWritablePath() + 'img/' + md5(clipurl) + '.mp3'; //暂时只用mp3
      cc.log(filepath);
      let orgclipId = cc.audioEngine.play(filepath, false, 0);
      cc.log('state:' + cc.audioEngine.getState(orgclipId) + ' orgclipId:' + orgclipId);
      while (cc.audioEngine.getState(orgclipId) == cc.audioEngine.AudioState.INITIALZING) {
        //等着
        //cc.log('waiting.....');
      }
      cc.log('state1:' + cc.audioEngine.getState(orgclipId));
      cc.audioEngine.pause(orgclipId);
      //cc.audioEngine.pauseAll();
      cc.log('state2:' + cc.audioEngine.getState(orgclipId));
      //这里给的同时，update就启动了 
      self.orgclipId = orgclipId;
      if (self.bookjson.explainclip) {

        //TODO 另一部分
        filepath = jsb.fileUtils.getWritablePath() + 'img/' + md5(explainurl) + '.mp3'; //暂时只用mp3
        //试试preload
        cc.audioEngine.preload(filepath, function() {
          cc.log('expfile:' + filepath);
          let explainclipId = cc.audioEngine.play(filepath, false, 0);


          cc.audioEngine.pause(explainclipId);
          self.explainclipId = explainclipId;
        });


      }
      cc.audioEngine.pauseAll();
      self.gotopage(self.currentpage - 1);

    }, function(ratio) {}, function() {});

  },
  autoplay: function() {
    let self = this;
    // cc.audioEngine.rewindMusic();
    let page = self.bookjson.pages[self.currentpage - 1];
    //this.scheduleOnce(self.gotopage(self.currentpage), page.len);
  },
  /**
   * 进行一下改造，改成全都从网上来？
   * @param  {[type]} book     [description]
   * @param  {[type]} bookjson [description]
   * @param  {[type]} index    [description]
   * @return {[type]}          [description]
   */
  gotopage: function(index) {
    var self = this;
    //if (cc.audioEngine.getState(self.orgclipId) == cc.audioEngine.AudioState.PLAYING) {
    cc.audioEngine.pause(self.orgclipId);
    //}
    // if (cc.audioEngine.isMusicPlaying()) {
    //   cc.audioEngine.stopMusic();
    // }
    //最后一页
    if (index >= self.bookjson.pages.length) {
      return;
    }
    //这是每本书读到哪里了
    cc.sys.localStorage.setItem(self.bookjson.id + '_readcount', self.currentpage);
    this.pagenum.getComponent(cc.Label).string = self.currentpage + "/" + self.bookjson.pages.length;
    this.status = 1;
    cc.log('index:' + index + ' length:' + self.bookjson.pages);
    //这里开始考虑使用xhrutils从网上取资源的情况
    var perfix = self.bookjson.perfix || '';
    //这里分为两种情况，一种是下载到本地的图片，另一种是没有下载的
    //会在图片Map中写入
    let picurl = perfix + self.bookjson.path + "/" + self.bookjson.pages[index].pic + '.' + (self.bookjson.pages[index].pictype ? self.bookjson.pages[index].pictype : 'jpg');
    let picfile = jsb.fileUtils.getWritablePath() + "img/" + md5(picurl) + '.' + (self.bookjson.pages[index].pictype ? self.bookjson.pages[index].pictype : 'jpg');

    if (!jsb.fileUtils.isFileExist(picfile)) {
      picfile = picurl;
    }
    //如果存在就直接跳转
    self.changepage(picfile, index);
  },
  changepage: function(picfile, index) {
    var fadeout = cc.fadeOut(1);
    var fadein = cc.fadeIn(1);
    let self = this;
    cc.log('pic:' + picfile);
    var finished = cc.callFunc(function(target, ind) {
      //这里对图像进行了重置，但采用的是sprite原始的scale
      self.book.getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(picfile); //.setTexture(pic);
      let pic = self.book.getComponent(cc.Sprite).spriteFrame.getTexture();
      //在这之后进行缩放调整几乎无效
      if (pic.pixelHeight > pic.pixelWidth) {
        //纵向--》以高进行缩放
        let rat = pic.pixelHeight / 720;
        self.book.height = pic.pixelHeight / rat;
        self.book.width = pic.width / rat;
      } else {
        //横向-->以宽进行缩放
        let rat = pic.pixelWidth / 720;
        self.book.width = pic.pixelWidth / rat;
        self.book.height = pic.height / rat;
      }
    }, this, index);
    var finished1 = cc.callFunc(function(target, ind) {
      self.status = 0;

      cc.audioEngine.setCurrentTime(self.orgclipId, self.bookjson.pages[self.currentpage - 1].orgcs);
      cc.audioEngine.setVolume(self.orgclipId, 1);
      self.orgce = self.bookjson.pages[self.currentpage - 1].orgce;
      if (cc.audioEngine.getState(self.orgclipId) == cc.audioEngine.AudioState.PAUSED) {
        cc.audioEngine.resume(self.orgclipId);
      } else {
        //  cc.audioEngine.play(self.orgclipId);
      }


      cc.log('orgce:' + self.orgce);


    }, this, index);

    var seq = cc.sequence(fadeout, finished, fadein, finished1);
    self.book.runAction(seq);
  },
  //重写bookdata.js文件
  writeBookDataFile: function(book_id) {
    if (!cc.sys.isNative) return;
    // let thisbook=bookdata[book_index];

    cc.sys.localStorage.setItem(book_id + '_last', new Date().getTime());
    //bookdata.
  },
  // called every frame, uncomment this function to activate update callback
  update: function(dt) {
    let self = this;
    //由帧控制音频的播放时间,这样以orgce来对是否进行播放控制。
    if (self.orgclipId) {
      cc.log('aid:' + self.orgclipId + ' time:' + cc.audioEngine.getCurrentTime(self.orgclipId) + ' state:' + cc.audioEngine.getState(self.orgclipId));
      //cc.log('bid:' + self.orgclipId + ' time:' + cc.audioEngine.getCurrentTime(self.orgclipId) + ' state:' + cc.audioEngine.getState(self.orgclipId));
    }
    if (self.explainclipId && self.explaince > 0) {
      cc.log('bid:' + self.explainclipId + ' time:' + cc.audioEngine.getCurrentTime(self.explainclipId) + ' state:' + cc.audioEngine.getState(self.explainclipId));
      //cc.log('bid:' + self.orgclipId + ' time:' + cc.audioEngine.getCurrentTime(self.orgclipId) + ' state:' + cc.audioEngine.getState(self.orgclipId));
    }

    if (self.orgclipId && self.orgce > 0) {
      if (cc.audioEngine.getState(self.orgclipId) == cc.audioEngine.AudioState.PLAYING) {
        //只有在playing状态时才能判断，其它状态不用判断
        //但当暂停时，与重新setCurrentTime，可能不是同时
        //会造成那边刚重置时间，并开始播放，这边正好进行判断而暂停。
        if (cc.audioEngine.getCurrentTime(self.orgclipId) >= self.orgce) {
          cc.log('currenttime' + cc.audioEngine.getCurrentTime(self.orgclipId) + ' orgce:' + self.orgce);
          //不要的话，一开始进来会慢一点，已经开始读了才进行
          //
          cc.audioEngine.pauseAll();
          if (self.auto) {
            self.autoGoto();
          }

        }
      }

    }

    if (self.explainclipId && self.explaince > 0) {
      if (cc.audioEngine.getState(self.explainclipId) == cc.audioEngine.AudioState.PLAYING) {
        if (cc.audioEngine.getCurrentTime(self.explainclipId) >= self.explaince) {
          cc.audioEngine.pauseAll();
        }
      }
    }

  },
  autoGoto: function() {
    let self = this;
    if (self.currentpage === self.bookjson.pages.length) return;
    self.currentpage = self.currentpage + 1;
    self.gotopage(self.currentpage - 1);
  }
});